package guardian.web
import com.mls.guardian.common.JsonUtil
import com.mls.guardian.config.helper.ConfigPathManagr
import com.mls.guardian.config.helper.PropConfigHelper
import com.mls.guardian.dataobj.ProcessMessage
import com.mls.guardian.dataobj.ServerProcessInfo
import com.mls.guardian.protocol.CodeType
import com.mls.guardian.protocol.RemoteBody
import com.mls.guardian.protocol.RemoteCommand
import com.mls.guardian.protocol.body.AppRestartBody
import com.mls.guardian.protocol.body.FileInfoBody
import com.mls.guardian.protocol.body.ServerProcessInfoBody
import com.mls.guardian.remoting.client.Client
import com.mls.guardian.remoting.netty.NettyClient
import com.mls.guardian.remoting.netty.RemoteTools
import vo.OperationLog
import vo.User

class IndexController {
    def Map result = ['suc':true,'message':'',data:[]]
    def operationService;
    def projectService;
    Client client = new NettyClient(null);
    def remoteIp = null;
    def index() {
        if(remoteIp == null){
            PropConfigHelper propConfigHelper = new PropConfigHelper();
            Properties properties = propConfigHelper.parse(ConfigPathManagr.getConfigPath());
            remoteIp = properties.getProperty("masterIp")+":"+properties.getProperty("masterPort");
        }
        render(contentType:"text/json") {
            result.suc = true;
            result.data = session.loginUser
            result
        }
    }

    def beforeInterceptor = {
        println "Tracing action ${actionUri}"
    }


    def list(){
        render(contentType:"text/json") {
            result.suc = true;
            ServerProcessInfoBody body = new ServerProcessInfoBody();
            body.setProjectName(params.projectName);
            RemoteCommand request = RemoteTools.getRequestRemoteCmd(CodeType.SERVER_PROCESS_INFO, body);
            RemoteCommand response = client.sendMessageSync(remoteIp, request, -1);
            ServerProcessInfoBody responseBody = (ServerProcessInfoBody) response.getRemoteBody();
            result.data = responseBody
            result
        }
    }


    def hasList(){
        render(contentType:"text/json") {
            result.suc = true;
            result.data = ["BaseService","SkuService","InService"]
            result
        } }

    def reStart(){
        User user = session.loginUser;
        OperationLog log = new OperationLog();
        def serverInfos = JsonUtil.deserialize(params["content"]);
        def optation = serverInfos.optation
        List<ServerProcessInfo> servers = new ArrayList()
        for(serverInfo in serverInfos.serverInfos){
            ServerProcessInfo si = new ServerProcessInfo();
            si.setIp(serverInfo.ip);
            List<ProcessMessage> processObjs = new ArrayList();
            for(process in serverInfo.processObj){
                ProcessMessage processObj = new ProcessMessage("",process);
                if(serverInfo.staticFiles!=null){
                    List<String> moduleFile = new ArrayList()
                    println serverInfo.staticFiles.length
                    serverInfo.staticFiles.each{
                        moduleFile.add(it.id)
                        println it.id
                    }
                    processObj.setModuleFile(moduleFile)
                }
                processObjs.add(processObj)
            }
            si.setProcessList(processObjs)
            servers.add(si);
        }
        AppRestartBody appRestart = new AppRestartBody();
        appRestart.setProjectName(serverInfos.projectName);
        appRestart.setServerProcessInfoListList(servers);
        RemoteCommand request = null
        if(optation=='restart'){
            log.setOperationType("发布升级")
            request = RemoteTools.getRequestRemoteCmd(CodeType.RESTART, appRestart);
        }else if(optation=='stop'){
            log.setOperationType("停止")
            request = RemoteTools.getRequestRemoteCmd(CodeType.STOP, appRestart);
        }else if(optation=='static'){
            log.setOperationType("静态更新")
            request = RemoteTools.getRequestRemoteCmd(CodeType.UPDATE_STATIC_FILE, appRestart);
        }else if(optation=='start'){
            log.setOperationType("重启")
            request = RemoteTools.getRequestRemoteCmd(CodeType.START, appRestart);
        }
        def date = new Date()
        log.setCreateTime(date)
        def startTimes =date.getTime()
        RemoteCommand response = client.sendMessageSync(remoteIp, request, -1);
        RemoteBody appRestartRes = response.getRemoteBody();
        result.data = appRestartRes;
        result.suc = appRestartRes.isSuc()
        log.setAppName(serverInfos.projectName)
        log.setCreateUser(user.getLoginName())
        log.setRemark(serverInfos.remark)
        log.setSuc(appRestartRes.isSuc())
        log.setRequest(JsonUtil.serialize(appRestart))
        log.setResponse(JsonUtil.serialize(appRestartRes))
        def alltimes = (new Date().getTime() - startTimes)/1000 as int;
        log.setCostTime(alltimes)
        log.setIp(getIp())
        if(result.suc){
            log.setVersion(((AppRestartBody)appRestartRes).getVersionTag())
        }
        operationService.save(log)
        render(contentType:"text/json") {
            result
        } }


    def reStore(){
        User user = session.loginUser;
        OperationLog log = new OperationLog()
        def version = params.version
        log.setVersion(version)
        def logs = operationService.searchAll(log)
        if(logs == null || logs.size()<=0){
            render(contentType:"text/json") {
                result.message = "版本号不存在"
                result.suc = false;
                result
            }
            return
        }
        def olDlog = logs.get(0);
        def appRestart = JsonUtil.deserialize(olDlog.request)
        AppRestartBody appRestore = new AppRestartBody();
        appRestore.setProjectName(olDlog.appName);
        appRestore.setVersionTag(version);//还原版本号
        List<ServerProcessInfo> servers = new ArrayList()
        appRestart.serverProcessInfoListList.each{
            ServerProcessInfo si = new ServerProcessInfo()
            si.setIp(it.ip)
            servers.add(si)
        }
        appRestore.setServerProcessInfoListList(servers);
        RemoteCommand  request = RemoteTools.getRequestRemoteCmd(CodeType.RESTORE, appRestore);
        log.setOperationType("还原")
        def date = new Date()
        log.setCreateTime(date)
        def startTimes =date.getTime()
        RemoteCommand response = client.sendMessageSync(remoteIp, request, -1);
        RemoteBody appRestartRes = response.getRemoteBody();
        result.data = appRestartRes;
        result.suc = appRestartRes.isSuc();
        log.setAppName(olDlog.appName)
        log.setCreateUser(user.getLoginName())
        log.setRemark(params.remark+"  ["+version+"]")
        log.setSuc(appRestartRes.isSuc())
        log.setRequest(JsonUtil.serialize(appRestore))
        log.setResponse(JsonUtil.serialize(appRestartRes))
        log.setVersion("")
        log.setIp(getIp())
        def alltimes = (new Date().getTime() - startTimes)/1000 as int;
        log.setCostTime(alltimes)
        operationService.save(log)
        render(contentType:"text/json") {
            result
        } }


    def searchLog(){
        render(contentType:"text/json") {
            result.data = operationService.searchAll(new OperationLog())
            result.suc = true;
            result
        }
    }

    def treeNode(){
        render(contentType:"text/json") {
            FileInfoBody fileInfoBody = new FileInfoBody();
            fileInfoBody.setProjectName(params.projectName);
            fileInfoBody.setModuleName(params.appName);
            if(params.parentId!="/"){
                fileInfoBody.setParent(params.parentId);
            }
            fileInfoBody.setIpAddress(params.ip)
            RemoteCommand request = RemoteTools.getRequestRemoteCmd(CodeType.GET_FILE_INFO, fileInfoBody);
            RemoteCommand response = client.sendMessageSync(remoteIp, request, -1);
            RemoteBody remoteBody = response.getRemoteBody();
            if (remoteBody.isSuc()) {
                def nodes = new ArrayList();
                FileInfoBody rtn = (FileInfoBody) remoteBody;
                rtn.children.each{
                    def isParent = false;
                    if(it.fileType.toString() == "FOLDER"){
                        isParent = true;
                    }
                    nodes.add([appName:params.appName,ip:params.ip,pId:params.parentId,name:it.fileName,isParent:isParent,id:it.filePath])
                }
                nodes
            }

        }
    }


    def projects(){
        render(contentType:"text/json") {
            result.data = projectService.searchAll()
            result.suc = true;
            result
        }
    }

    def getIp(){
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    def ownUpgrade(){
        User user = session.loginUser;
        OperationLog log = new OperationLog();
        log.setAppName("owner")
        log.setCreateUser(user.getLoginName())
        log.setRemark("自我修复")
        log.setRemark(params.remark)
        log.setSuc(true)
        log.setVersion("")
        log.setIp(getIp())
        def date = new Date()
        log.setCreateTime(date)
        AppRestartBody requestBody = new AppRestartBody();
        RemoteCommand request = RemoteTools.getRequestRemoteCmd(CodeType.UPGRADE, requestBody);
        client.sendMessageOneWay(remoteIp, request);
        result.suc = true;
        operationService.save(log)
        render(contentType:"text/json") {
            result
        }
    }

}
